package com.example.admin.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;


@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter
{

    //使用BCrypt加密策略
    @Bean
    public BCryptPasswordEncoder bCryptPasswordEncoder()
    {
        return new BCryptPasswordEncoder();
    }

    public static void main(String[] args)
    {
        //加密策略 MD5 不安全 彩虹表  MD5 加盐
        String mszlu = new BCryptPasswordEncoder().encode("mszlu");
    }

    @Override
    public void configure(WebSecurity web) throws Exception
    {
        super.configure(web);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception
    {
        //开启登录认证
        http.authorizeRequests()
                .antMatchers("/css/**").permitAll()
                .antMatchers("/img/**").permitAll()
                .antMatchers("/js/**").permitAll()
                .antMatchers("/plugins/**").permitAll()

                .antMatchers("/admin/**").access("@authService.auth(request,authentication)") //自定义service实现实时的权限认证
                .antMatchers("/pages/**").authenticated();

        //没有权限，会自动跳到登陆页,需要开启登录的页面
        http.formLogin()
                .loginPage("/login.html") //自定义的登录页面
                .loginProcessingUrl("/login") //登录处理接口
                .usernameParameter("username") //定义登录时的用户名的key 默认为username
                .passwordParameter("password") //定义登录时的密码key，默认是password
                .defaultSuccessUrl("/pages/main.html") //登录成功跳转的页面
                .failureUrl("/login.html") //登录失败跳转的页面
                .permitAll(); //和登录表单相关的接口/login通过


        //退出登录配置
        http.logout()
                .logoutUrl("/logout") //退出登录接口
                .logoutSuccessUrl("/login.html") //退出登录成功跳转的页面
                .permitAll(); //退出登录的接口放行

        http.httpBasic()
            .and()
            .csrf().disable() //csrf关闭 如果自定义登录 需要关闭
            .headers().frameOptions().sameOrigin();//支持iframe嵌套
    }
}
